<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class BaseModel extends Model
{
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    public function __construct()
    {
        $this->run();
    }

    /**
     * 运行表结构
     */
    protected function run()
    {
        //运行建表语句
        $tableName = $this->subTableRole();
        if (!empty($tableName)) {
            $this->setTable($tableName);
        } else {
            $tableName = $this->getTable();
        }
        if (!empty(env('DB_PREFIX')) && !strpos($tableName, env('DB_PREFIX'))) {
            $tableName = env('DB_PREFIX') . $tableName;
        }
        $tableSql = $this->buildTable($tableName);
        $cache = Cache::get($tableName);
        if (empty($cache) && !empty($tableSql)) {
            $isTable = DB::statement($tableSql);
            if ($isTable) {
                Cache::forever($tableName, 1);
            }
        }
        $field = $this->bulidField();

        if (!empty($field) && is_array($field)) {
            foreach ($field as $key => $v) {
                $res = Cache::get($tableName . '_' . $key);
                // var_dump($res, 1111111);
                if ($res) {
                    continue;
                }
                $fieldSqlAll = "select COLUMN_NAME as FIELDS from INFORMATION_SCHEMA.Columns where table_name= '$tableName'";
                $resField = DB::select($fieldSqlAll);
                if (!empty($resField)) {
                    $resField = array_column($resField, 'FIELDS');
                }
                if (in_array($key, $resField)) {
                    Cache::forever($tableName . '_' . $key, 1);
                    continue;
                }
                if (!Cache::get($tableName . '_' . $key) && !in_array($key, $resField)) {
                    $fieldSql = 'ALTER TABLE ' . $tableName . ' ADD ' . $key . ' ' . $v;
                    $isField = DB::statement($fieldSql);
                    if ($isField) {
                        Cache::forever($tableName . '_' . $key, 1);
                    }
                }
            }
        }
    }

    public function aliasRable($alias)
    {
        return $this->setTable($alias);
    }

    //返回关键字段
    public function getTableField()
    {
        return $this->fillable;
    }

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected function buildTable()
    {
    }

    protected function bulidField()
    {
    }

    //分表规则
    public function subTableRole()
    {
    }

    //联合查询
    public function setUnionAllTable($start_time, $end_time)
    {
    }
}
